package com.itheima.producer;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/*
 * 发送消息
 * */
public class Producer_Routing {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2.设置参数
        factory.setHost("172.81.237.219");//ip地址
        factory.setPort(5672);
        factory.setVirtualHost("/itcast");//虚拟机
        factory.setUsername("heima");
        factory.setPassword("heima");
        //3.创建连接
        Connection connection = factory.newConnection();
        //4.创建channel
        Channel channel = connection.createChannel();

        //5.创建交换机
        /*
        * String exchange, 交换机名
        * BuiltinExchangeType type, 交换机类型
        *           DIRECT("direct"),定向
                    FANOUT("fanout"),扇形（广播）发送消息到每一个与之绑定的队列
                    TOPIC("topic"),通配符
                    HEADERS("headers");参数
        * boolean durable,是否持久化
        * boolean autoDelete,是否自动删除
        * boolean internal,是否内部使用
        * Map<String, Object> arguments参数列表
        * */
        String exchangeName = "test_direct";
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT,true,false,false,null);

        //6.创建队列
        String queue1Name="test_direct_queue1";
        String queue2Name="test_direct_queue2";
        channel.queueDeclare(queue1Name,true,false,false,null);
        channel.queueDeclare(queue2Name,true,false,false,null);


        //7.绑定队列和交换机
        /*
        * String queue,队列名称
        * String exchange,交换机名称
        * String routingKey，路由键，绑定规则
        * */
        //队列1的绑定
        channel.queueBind(queue1Name,exchangeName,"error");
        //队列2的绑定
        channel.queueBind(queue2Name,exchangeName,"info");
        channel.queueBind(queue2Name,exchangeName,"error");
        channel.queueBind(queue2Name,exchangeName,"warning");


        //8.发送消息
        String body="日志信息：张三调用了delete方法，日志级别为：error";
        channel.basicPublish(exchangeName,"warning",null,body.getBytes());

        //9.释放资源
        channel.close();
        connection.close();



    }
}
